package main

import (
	"encoding/json"
	"github.com/gorilla/mux"
	"github.com/redis/go-redis/v9"
	"github.com/rs/cors"
	"log"
	"net/http"
)

var rdb redis.UniversalClient

func SetKeyHandler(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	key := params["key"]
	value := params["value"]

	err := rdb.Set(r.Context(), key, value, 0).Err()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	json.NewEncoder(w).Encode("Key set successfully")
}

func GetKeyHandler(w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)
	key := params["key"]

	val, err := rdb.Get(r.Context(), key).Result()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	json.NewEncoder(w).Encode(val)
}

func main() {
	// 定义 Redis 集群节点
	clusterNodes := []string{"192.168.30.223:7001", "192.168.30.223:7002", "192.168.30.223:7003",
		"192.168.30.225:7001", "192.168.30.225:7002", "192.168.30.225:7003"}
	//clusterNodes := []string{"redis-0.redis.redis-app:6379",
	//	"redis-1.redis.redis-app:6379",
	//	"redis-2.redis.redis-app:6379",
	//	"redis-3.redis.redis-app:6379",
	//	"redis-4.redis.redis-app:6379",
	//	"redis-5.redis.redis-app:6379"}
	//clusterNodes := []string{"localhost:6379"}
	redisConfig := &redis.UniversalOptions{
		Addrs: clusterNodes,
		//IdleTimeout:  conf.Pool.IdleTimeout,
		//MinIdleConns: conf.Pool.MinIdle,
		//PoolSize:     conf.Pool.MaxActive,
		//Password:     conf.Password,
		MaxRetries: 0,
	}
	// 创建集群客户端
	rdb = redis.NewUniversalClient(redisConfig)

	// 初始化路由
	router := mux.NewRouter()
	router.HandleFunc("/set/{key}/{value}", SetKeyHandler).Methods("POST")
	router.HandleFunc("/get/{key}", GetKeyHandler).Methods("GET")

	// 启动CORS
	handler := cors.Default().Handler(router)

	// 启动HTTP服务器
	log.Fatal(http.ListenAndServe(":18080", handler))
}
